/*
 * @Author: 溜溜的陈 525767273@qq.com
 * @Date: 2024-12-24 10:36:47
 * @LastEditors: 溜溜的陈 525767273@qq.com
 * @LastEditTime: 2025-01-02 15:57:42
 * @FilePath: \express-serve\router\user.js
 * @Description: 路由模块---用户登录和注册
 */
const express = require('express');
const jwt = require('jsonwebtoken')// token

const secretKey = 'chen@liu%liu#5257'
const db = require('../config/db');
const router = express.Router();
// 用户登录
router.post('/login', (req, res) => {
    let { userName, userPwd } = req.body;
    let sql = 'select * from user where userName=?'

    db.dbConfig(sql, [userName], (err, data) => {
        if (err) {
            res.send('查询失败')
        } else {
            console.log(data, 'data');
            if (data.length == 0) {
                return res.status(401).send({ code: 50001, msg: '用户名或密码错误' })
            } else {
                if (data[0].userPwd == userPwd) {
                    const token = jwt.sign({ userName }, secretKey, { expiresIn: '2h' });
                    const bearerToken = `Bearer ${token}`;
                    console.log(bearerToken, 'token');
                    res.status(200).send({ code: 200, msg: '登录成功', data: { token: token } })
                } else {
                    res.status(401).send({ code: 50001, msg: '用户名或密码错误' })
                    next(new Error('用户名或密码错误'))
                }

            }

        }
    })

})
// 用户注册//这块要写一个图形验证码，防止恶意注册
router.post('/register', (req, res) => {
    res.status(200).send({ code: 200, msg: '成功', data: { info: '测试信息' } })

})


module.exports = router
